import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { nebulaExec } from '@/utils/request'

export const useSchemaStore = defineStore('schemas', () => {
  const schemas = ref({})
  const loaded = ref(false)

  async function load() {
    if (loaded.value) {
      return
    }
    const tags = await nebulaExec('show tags')
    const promises = tags.Name.map((t: string) => nebulaExec(`desc tag ${t}`))
    const resps = await Promise.all(promises)
    tags.Name.forEach((t: string, idx: number) => {
      if (!resps[idx].Field) {
        return
      }
      schemas.value[t] = Object.fromEntries(
        resps[idx].Field.map((field: string, idx1: number) => [field, resps[idx].Comment[idx1]]),
      )
    })
    {
      const edges = await nebulaExec('show edges')
      const promises = edges.Name.map((t: string) => nebulaExec(`desc edge ${t}`))
      const resps = await Promise.all(promises)
      edges.Name.forEach((t: string, idx: number) => {
        if (!resps[idx].Field) {
          return
        }
        schemas.value[t] = Object.fromEntries(
          resps[idx].Field.map((field: string, idx1: number) => [field, resps[idx].Comment[idx1]]),
        )
      })
    }
    loaded.value = true
  }

  return { schemas, load }
})
